import 'package:flutter/material.dart';
import 'package:syncfusion_flutter_datagrid/datagrid.dart';

class DataTableDemo extends StatefulWidget {
  const DataTableDemo({Key? key}) : super(key: key);

  @override
  State<DataTableDemo> createState() => _DataTableDemoState();
}

class _DataTableDemoState extends State<DataTableDemo> {
  var _sortAscending = true;
  int? _sortColumn;

  final dataModels = <DataModel>[
    DataModel(nation: '中国', population: 14.1, continent: '亚洲'),
    DataModel(nation: '美国', population: 2.42, continent: '北美洲'),
    DataModel(nation: '俄罗斯', population: 1.43, continent: '欧洲'),
    DataModel(nation: '巴西', population: 2.14, continent: '南美洲'),
    DataModel(nation: '印度', population: 13.9, continent: '亚洲'),
    DataModel(nation: '德国', population: 0.83, continent: '欧洲'),
    DataModel(nation: '埃及', population: 1.04, continent: '非洲'),
    DataModel(nation: '澳大利亚', population: 0.26, continent: '大洋洲'),
    DataModel(nation: '印度', population: 13.9, continent: '亚洲'),
    DataModel(nation: '德国', population: 0.83, continent: '欧洲'),
    DataModel(nation: '埃及', population: 1.04, continent: '非洲'),
    DataModel(nation: '澳大利亚', population: 0.26, continent: '大洋洲'),
  ];

  Function(int, bool)? _sortCallback;

  @override
  void initState() {
    super.initState();
    _sortCallback = (int column, bool isAscending) {
      setState(() {
        _sortColumn = column;
        _sortAscending = isAscending;
      });
    };
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(
        title: const Text('DataTable'),
        backgroundColor: Colors.red[400]!,
      ),
      body: SingleChildScrollView(
        scrollDirection: Axis.vertical,
        child: SingleChildScrollView(
          scrollDirection: Axis.horizontal,
          child: DataTable(
            horizontalMargin: 10.0,
            showBottomBorder: true,
            sortAscending: _sortAscending,
            sortColumnIndex: _sortColumn,
            showCheckboxColumn: true,
            headingTextStyle: const TextStyle(
              fontWeight: FontWeight.bold,
              color: Colors.black,
            ),
            columns: [
              const DataColumn(label: Text('国家')),
              DataColumn(
                label: const Text('人口（亿）'),
                numeric: true,
                onSort: _sortCallback,
              ),
              DataColumn(
                label: const Text('大洲'),
                onSort: _sortCallback,
              ),
              const DataColumn(label: Text('说明')),
            ],
            rows: sortDataModels(),
          ),
        ),
      ),
    );
  }

  List<DataRow> sortDataModels() {
    dataModels.sort((dataModel1, dataModel2) {
      bool isAscending = _sortAscending;
      var result = 0;
      if (_sortColumn == 0) {
        result = dataModel1.nation.compareTo(dataModel2.nation);
      }
      if (_sortColumn == 1) {
        result = dataModel1.population.compareTo(dataModel2.population);
      }
      if (_sortColumn == 2) {
        result = dataModel1.continent.compareTo(dataModel2.continent);
      }

      if (isAscending) {
        return result;
      }

      return -result;
    });
    return dataModels
        .map((dataModel) => DataRow(
              onSelectChanged: (selected) {},
              cells: [
                DataCell(
                  Text(dataModel.nation),
                ),
                DataCell(
                  Text('${dataModel.population}'),
                ),
                DataCell(
                  Text(dataModel.continent),
                ),
                const DataCell(
                  Text('这是详细介绍'),
                ),
              ],
            ))
        .toList();
  }
}

class DataModel {
  final double population;
  final String nation;
  final String continent;

  DataModel({
    required this.nation,
    required this.population,
    required this.continent,
  });
}

class SFDataGridDemo extends StatefulWidget {
  const SFDataGridDemo({Key? key}) : super(key: key);

  @override
  State<SFDataGridDemo> createState() => _SFDataGridDemoState();
}

class _SFDataGridDemoState extends State<SFDataGridDemo> {
  final dataModels = <DataModel>[
    DataModel(nation: '中国', population: 14.1, continent: '亚洲'),
    DataModel(nation: '美国', population: 2.42, continent: '北美洲'),
    DataModel(nation: '俄罗斯', population: 1.43, continent: '欧洲'),
    DataModel(nation: '巴西', population: 2.14, continent: '南美洲'),
    DataModel(nation: '印度', population: 13.9, continent: '亚洲'),
    DataModel(nation: '德国', population: 0.83, continent: '欧洲'),
    DataModel(nation: '埃及', population: 1.04, continent: '非洲'),
    DataModel(nation: '澳大利亚', population: 0.26, continent: '大洋洲'),
    DataModel(nation: '印度', population: 13.9, continent: '亚洲'),
    DataModel(nation: '德国', population: 0.83, continent: '欧洲'),
    DataModel(nation: '埃及', population: 1.04, continent: '非洲'),
    DataModel(nation: '澳大利亚', population: 0.26, continent: '大洋洲'),
  ];

  final columnWidth = {
    'nation': double.nan,
    'population': double.nan,
    'continent': double.nan,
    'desc': double.nan
  };

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('SfDataGrid'),
        backgroundColor: Colors.red[400]!,
      ),
      body: Center(
        child: SfDataGrid(
          headerRowHeight: 40.0,
          frozenColumnsCount: 1,
          columnWidthMode: ColumnWidthMode.none,
          gridLinesVisibility: GridLinesVisibility.both,
          headerGridLinesVisibility: GridLinesVisibility.both,
          selectionMode: SelectionMode.single,
          columnResizeMode: ColumnResizeMode.onResize,
          allowColumnsResizing: true,
          onColumnResizeUpdate: (detail) {
            setState(() {
              columnWidth[detail.column.columnName] = detail.width;
            });
            return true;
          },
          source: NationDataSource(dataModels: dataModels),
          columns: [
            GridColumn(
              width: columnWidth['nation']!,
              columnName: 'nation',
              label: Container(
                color: Colors.blue[200],
                padding: const EdgeInsets.all(8.0),
                alignment: Alignment.centerLeft,
                child: const Text(
                  '国家',
                ),
              ),
            ),
            GridColumn(
              width: columnWidth['population']!,
              columnName: 'population',
              label: Container(
                color: Colors.blue[200],
                padding: const EdgeInsets.all(8.0),
                alignment: Alignment.centerRight,
                child: const Text(
                  '人口（亿）',
                ),
              ),
            ),
            GridColumn(
              width: columnWidth['continent']!,
              columnName: 'continent',
              label: Container(
                color: Colors.blue[200],
                padding: const EdgeInsets.all(8.0),
                alignment: Alignment.centerLeft,
                child: const Text(
                  '大洲',
                ),
              ),
            ),
            GridColumn(
              width: columnWidth['desc']!,
              columnName: 'desc',
              label: Container(
                color: Colors.blue[200],
                padding: const EdgeInsets.all(8.0),
                alignment: Alignment.centerLeft,
                child: const Text(
                  '说明',
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}

class NationDataSource extends DataGridSource {
  NationDataSource({required List<DataModel> dataModels}) {
    _dataModels = dataModels
        .map<DataGridRow>((e) => DataGridRow(cells: [
              DataGridCell<String>(columnName: 'nation', value: e.nation),
              DataGridCell<double>(
                  columnName: 'population', value: e.population),
              DataGridCell<String>(columnName: 'continent', value: e.continent),
              const DataGridCell<String>(columnName: 'desc', value: '这是详细介绍'),
            ]))
        .toList();
  }

  List<DataGridRow> _dataModels = [];

  @override
  List<DataGridRow> get rows => _dataModels;

  @override
  DataGridRowAdapter? buildRow(DataGridRow row) {
    return DataGridRowAdapter(
        cells: row.getCells().map<Widget>((dataGridCell) {
      return Container(
        alignment: (dataGridCell.columnName == 'population')
            ? Alignment.centerRight
            : Alignment.centerLeft,
        padding: const EdgeInsets.all(8.0),
        child: Text(dataGridCell.value.toString()),
      );
    }).toList());
  }
}
